﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data.Linq;
using Slam.Configuration;
using Slam.Data;

namespace Slam.Logging
{
	public class DefaultLog : ILog
	{
		private DefaultLogSettings _settings;
		public DefaultLog(SPSite site, DefaultLogSettings settings)
		{

		}

		public void BeginWriteEvent(EventType eventType, string typeName, string message)
		{
			throw new NotImplementedException();
		}

		public void EndWriteEvent()
		{
			throw new NotImplementedException();
		}

		public void WriteEvent(EventType eventType, string typeName, string message)
		{
			using (DataContext context = new DataContext(_settings.ConnectionString))
			{
				string valueString = String.Format("convert(datetime, '{0}', 101), '{1}', '{2}', '{3}'", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), eventType.ToString(), typeName.Replace("'", "''"), message.Replace("'", "''"));

				try
				{
					context.ExecuteCommand(SlamItemContext.CommitActivity, String.Format(Queries.InsertLogItem, Constants.Data.DataSchema, Constants.Data.EventLogTableName, valueString));
				}
				catch (Exception ex)
				{
					ExceptionEmailer.Send(SPContext.Current.Site.RootWeb, _settings.ErrorEmailToAddress, new Exception("Logging error: " + String.Format(Queries.InsertLogItem, Constants.Data.DataSchema, Constants.Data.EventLogTableName, valueString) + Environment.NewLine + ex.ToString()));
				}
			}
		}

		public void WriteException(Exception ex)
		{
			WriteMessage(MessageSeverity.Error, ex.ToString());
			ExceptionEmailer.Send(SPContext.Current.Site.RootWeb, _settings.ErrorEmailToAddress, ex);
		}

		public void WriteMessage(MessageSeverity severity, string message)
		{
			if (severity >= _settings.SeverityThreshold)
			{
				using (DataContext context = new DataContext(_settings.ConnectionString))
				{
					string valueString = String.Format("convert(datetime, '{0}', 101), '{1}', '{2}'", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss.fff"), severity.ToString(), message.Replace("'", "''"));
					try
					{
						context.ExecuteCommand(SlamItemContext.CommitActivity, String.Format(Queries.InsertLogItem, Constants.Data.DataSchema, Constants.Data.MessageLogTableName, valueString));
					}
					catch (Exception ex)
					{
						ExceptionEmailer.Send(SPContext.Current.Site.RootWeb, _settings.ErrorEmailToAddress, new Exception("Logging error: " + String.Format(Queries.InsertLogItem, Constants.Data.DataSchema, Constants.Data.MessageLogTableName, valueString) + Environment.NewLine + ex.ToString()));
					}
				}
			}
		}
	}
}
